package com.sgt.frp.service;


import cn.hutool.core.util.ZipUtil;
import com.sgt.frp.VO.FrpConnect;
import com.sgt.frp.excepiton.BusinessException;
import com.sgt.frp.utils.IniUtils;
import com.sgt.frp.utils.MyFileUtil;
import org.ini4j.Ini;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class FrpService {

    @Value("${frpserver.address}")
    String serveAddr;

    @Value("${frpserver.port}")
    Integer servePort;

    @Value("${baseFilePath}")
    String baseFilePath;

    public Boolean createFrpConnect(FrpConnect frpConnect) {
        File file=null;
        if(frpConnect.getClientType()==1){
            file = new File("frp_win/frpc.ini");
        }else if(frpConnect.getClientType()==2){
            file = new File("frp_mac/frpc.ini");
        }else{
            file = new File("frp_linux/frpc.ini");
        }
        Ini iniFile=null;
        try{
            iniFile= MyFileUtil.initIniFile(file,frpConnect);
        }catch (BusinessException e){
            throw BusinessException.init(e.getMsg());
        }
        IniUtils.setCommonMsg(iniFile, serveAddr, servePort);
        if(frpConnect.getType().contains("http")){
            IniUtils.setHttpOrHttpsMsg(iniFile, frpConnect);
        }else{
            IniUtils.setTcpOrUdp(iniFile, frpConnect);
        }
        try {
            iniFile.store(file);
        } catch (IOException e) {
            throw BusinessException.init("保存配置文件失败");
        }
        if(frpConnect.getClientType()==1){
            ZipUtil.zip(baseFilePath+"frp_win",baseFilePath+"frp.zip");
        }else if(frpConnect.getClientType()==2){
            ZipUtil.zip(baseFilePath+"frp_mac",baseFilePath+"frp.zip");
        }else {
            ZipUtil.zip(baseFilePath+"frp_linux",baseFilePath+"frp.zip");
        }
        return true;
    }
}
